package com.lee.springCloud.controller;

import com.lee.springCloud.domain.CommonResult;
import com.lee.springCloud.domain.Payment;
import com.lee.springCloud.serveice.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Lee
 * @createDate 2021/12/22 14:10
 */
@Controller
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Resource
    private DiscoveryClient discoveryClient;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping(value = "/payment/create")
    @ResponseBody
    public CommonResult create(@RequestBody Payment payment){
        CommonResult commonResult = paymentService.create(payment);
        return commonResult;
    }

    @GetMapping(value = "/payment/get/{id}")
    @ResponseBody
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        CommonResult commonResult = paymentService.getPaymentById(id);
        return commonResult;
    }

    @GetMapping("/payment/discovery")
    @ResponseBody
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for(String element : services){
            log.info("*****入驻服务名称："+element);
        }
        //获取 "CLOUD-PAYMENT-SERVICE" 服务下相关信息
        //CLOUD-PAYMENT-SERVICE为服务提供者Application名称yml文件中可找到
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance instance : instances){
            //输出结果为 CLOUD-PAYMENT-SERVICE===192.168.110.198===8001===http://192.168.110.198:8001
            log.info(instance.getServiceId()+"==="+instance.getHost()+"==="+instance.getPort()+"==="+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    @ResponseBody
    public String getPaymentLb(){
        return serverPort;
    }

}
